package cn.pugle.selenium;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 因为懒，就把driver写死在静态里了 <br>
 *webdriver.chrome.driver=chromedriver.exe <br>
 * Created by tzp on 5/17/16.<br>
 */
public class SeleUtil {
    private static final Logger logger = LoggerFactory.getLogger(SeleUtil.class);
    public static final String Default_Charset = "UTF-8";
    public static RemoteWebDriver chromeDriver;

    static {
        chromeDriver = new ChromeDriver();
        chromeDriver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
        chromeDriver.manage().timeouts().setScriptTimeout(6, TimeUnit.SECONDS);
    }

    public static By by(String by) {
        char c = by.charAt(0);
        switch (c) {
            case '.': {
                return By.className(by.substring(1));
            }
            case '#': {
                return By.id(by.substring(1));
            }
            case 'x':{
                return By.xpath(by.substring(1));
            }
            default: {
                return By.cssSelector(by);
            }
        }
    }

    public static WebElement waitElementPresent(By by) throws Exception {
        for (int second = 0; ; second++) {
            if (second >= 32)
                throw new Exception("timeout");
            try {
                if (isElementPresent(by)) break;
            } catch (Exception e) {
            }
            Thread.sleep(1000);
        }
        return chromeDriver.findElement(by);
    }

    public static void waitElementDisappear(By by) throws Exception {
        for (int second = 0; ; second++) {
            if (second >= 32)
                throw new Exception("timeout");
            try {
                if (!isElementPresent(by)) break;
            } catch (Exception e) {
            }
            Thread.sleep(1000);
        }
    }
    /*设置等待秒数*/
    public static void waitElementDisappear(By by, int time) throws Exception {
        for (int second = 0; ; second++) {
            if (second >= time)
                throw new Exception("timeout");
            try {
                if (!isElementPresent(by)) break;
            } catch (Exception e) {
            }
            Thread.sleep(1000);
        }
    }

    public static boolean isElementPresent(By by) {
        try {
            chromeDriver.findElement(by);
            return true;
        } catch (NoSuchElementException e) {
            return false;
        }
    }

    /**
     * 从json文件中导入cookie,使用chrome EditThisCookie导出
     */
    public static boolean addCookie(String file) {
        WebDriver.Options manage = chromeDriver.manage();
        try {
            JSONArray cookies = JSON.parseArray(IOUtils.toString(ClassLoader.getSystemResourceAsStream(file), Default_Charset));
            for (int i = 0; i < cookies.size(); i++) {
                JSONObject cookie = cookies.getJSONObject(i);
                manage.addCookie(
                        new Cookie(cookie.getString("name"),
                                cookie.getString("value"),
                                cookie.getString("domain"),
                                cookie.getString("path"),
                                cookie.getDate("expirationDate"),
                                cookie.getBoolean("secure")
                        ));
            }

        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 尝试get直到条件达成或超过次数
     */
    public static boolean tryGet(RemoteWebDriver chromeDriver, String url, By condition, boolean present, int times) {
        for (int i = 0; i < times; i++) {
            chromeDriver.get(url);
            try {
                if (present) {
                    waitElementPresent(condition);
                } else {
                    waitElementDisappear(condition);
                }
            } catch (Exception e) {
                logger.info("try {} timeout {}", url, i);
                continue;
            }
            return true;
        }
        return false;
    }

    /**
     * 自己写的wait效果不好
     */
    @Deprecated
    private static WebElement waitElementShit(WebDriver chromeDriver, final By by) {
        System.out.println("wait in");
        WebDriverWait wait = new WebDriverWait(chromeDriver, 10);
        WebElement e = wait.until(new ExpectedCondition<WebElement>() {
            @Override
            public WebElement apply(WebDriver d) {
                return d.findElement(by);
            }

            @Override
            public boolean equals(Object o) {
                return false;
            }
        });
        System.out.println("wait out");
        return e;
    }
}
